from os.path import join as pjoin

from numscons import GetNumpyEnvironment
from numscons import CheckF77LAPACK, CheckF77Clib
from numscons import write_info, IsAccelerate, IsVeclib

env = GetNumpyEnvironment(ARGUMENTS)

#=======================
# Starting Configuration
#=======================
config = env.NumpyConfigure(custom_tests = {'CheckLAPACK' : CheckF77LAPACK,
                                            'CheckF77Clib' : CheckF77Clib})

env.Tool('f2py')
#-----------------
# Checking Lapack
#-----------------
st = config.CheckF77Clib()
st = config.CheckLAPACK(autoadd = 1)
if not st:
    raise RuntimeError("no lapack found, necessary for arpack module")

use_c_calling = IsAccelerate(env, "lapack") or IsVeclib(env, "lapack")
config.Finish()
write_info(env)

# Build arpack
arpack_src = [pjoin("ARPACK", "SRC", s) for s in [ "cgetv0.f", "cnaitr.f",
"cnapps.f", "cnaup2.f", "cnaupd.f", "cneigh.f", "cneupd.f", "cngets.f",
"csortc.f", "cstatn.f", "dgetv0.f", "dlaqrb.f", "dnaitr.f", "dnapps.f",
"dnaup2.f", "dnaupd.f", "dnconv.f", "dneigh.f", "dneupd.f", "dngets.f",
"dsaitr.f", "dsapps.f", "dsaup2.f", "dsaupd.f", "dsconv.f", "dseigt.f",
"dsesrt.f", "dseupd.f", "dsgets.f", "dsortc.f", "dsortr.f", "dstatn.f",
"dstats.f", "dstqrb.f", "sgetv0.f", "slaqrb.f", "snaitr.f", "snapps.f",
"snaup2.f", "snaupd.f", "snconv.f", "sneigh.f", "sneupd.f", "sngets.f",
"ssaitr.f", "ssapps.f", "ssaup2.f", "ssaupd.f", "ssconv.f", "sseigt.f",
"ssesrt.f", "sseupd.f", "ssgets.f", "ssortc.f", "ssortr.f", "sstatn.f",
"sstats.f", "sstqrb.f", "zgetv0.f", "znaitr.f", "znapps.f", "znaup2.f",
"znaupd.f", "zneigh.f", "zneupd.f", "zngets.f", "zsortc.f", "zstatn.f"]]

arpack_src += [pjoin('ARPACK', 'UTIL', s) for s in [ "cmout.f", "cvout.f",
"dmout.f", "dvout.f", "icnteq.f", "icopy.f", "iset.f", "iswap.f", "ivout.f",
"second.f", "smout.f", "svout.f", "zmout.f", "zvout.f"]]

if use_c_calling:
    arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_f.f'),
                   pjoin('ARPACK', 'FWRAPPERS', 'veclib_cabi_c.c')]
else:
    arpack_src += [pjoin('ARPACK', 'FWRAPPERS', 'dummy.f')]
arpack_src += [pjoin('ARPACK', 'LAPACK', s) for s in [ "clahqr.f", "dlahqr.f",
"slahqr.f", "zlahqr.f"]]

src = [str(s) for s in arpack_src]

env.AppendUnique(CPPPATH = [pjoin('ARPACK', 'SRC')])
env.AppendUnique(F77PATH = [pjoin('ARPACK', 'SRC')])
env.AppendUnique(LIBPATH = ['.'])
arpack_lib = env.DistutilsStaticExtLibrary('arpack', source = src)

# Build _arpack extension
env.FromFTemplate('arpack.pyf', 'arpack.pyf.src')
env.Prepend(LIBS = 'arpack')
env.NumpyPythonExtension('_arpack', 'arpack.pyf')
